package network.ssl;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;

import ucp.projects.kraken.kamcenter.plugin.CameraFrame;


public class KrakenSSLThreadSendImage implements Runnable {
	
	private Thread thread;
	private KrakenSSLCommandInterpreter krakenSSLComandInterpreter;
	private String cameraName;
	private String numService;
	private int fps_max;
	private boolean goOn;
	
	public KrakenSSLThreadSendImage(KrakenSSLCommandInterpreter sslCI, String camName, String numServ, int fps){
		this.krakenSSLComandInterpreter = sslCI;
		this.cameraName = camName;
		this.numService = numServ;
		this.fps_max = fps;
		this.goOn = true;
		thread = new Thread(this);
		thread.start();
	}
	
	@Override
	public void run() {
		ObjectOutputStream outputStream;
		CameraFrame frame = this.krakenSSLComandInterpreter.getKrakenThread().getKrakenSSLServer().getKrakenImageThreadServer().getFramesMap().get(this.cameraName);
		long savedTimestamp = frame.getTimestamp();
		Date date = new Date();
		long controlFPS = date.getTime();
		long timeNow, delai = (1/fps_max)*1000;
		int fps;
		
		try {
			outputStream = new ObjectOutputStream(this.krakenSSLComandInterpreter.getKrakenThread().getSocket().getOutputStream());
			while(goOn){
				fps = this.krakenSSLComandInterpreter.getKrakenThread().getKrakenSSLServer().getStreamingServiceFPSMap().get(this.numService);
				if(fps == 0 || fps > fps_max) fps = fps_max;
				
				timeNow = new Date().getTime();
				delai = (1/fps)*1000;
				if((timeNow - controlFPS) > delai){
					frame = this.krakenSSLComandInterpreter.getKrakenThread().getKrakenSSLServer().getKrakenImageThreadServer().getFramesMap().get(this.cameraName);
					if(frame.getTimestamp() > savedTimestamp){
						savedTimestamp = frame.getTimestamp();
						//System.out.println("ImageToSend");
						outputStream.writeUnshared(frame);
						//outputStream.reset();
						//System.out.println("ImageSend");
						date = new Date();
						controlFPS = date.getTime();
						//System.out.println("ImageSend"+controlFPS);
					}
					else{
						//System.out.println("NoNewImage");
					}	
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void pauseThreadSendImage(){
		this.thread.interrupt();
		System.out.println("Pause:pauseThreadSendImage");
	}
	
	public void goOnThreadSendImage(){
		if(this.thread.isInterrupted()){
			this.thread.run();
			System.out.println("Play:goOnThreadSendImage");
		}
	}
	
	public void stopThreadSendImage(){
		this.goOn = false;
		System.out.println("Stop:stopThreadSendImage");
	}

}
